package cn.aopmin.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置类
 *
 * @author 白豆五
 * @since 2024/7/4
 */
@Configuration
public class DataSourceConfig {

    //定义数据源1
    @Bean("ds1")
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource ds1() {
        return DataSourceBuilder.create().build();
    }

    //定义数据源2
    @Bean("ds2")
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSource ds2() {
        return DataSourceBuilder.create().build();
    }

    //定义动态数据源,建立在DataSource基础上, 动态数据源需要实现AbstractRoutingDataSource
    @Bean(name = "dataSource")
    public DataSource dynamicDataSource(@Qualifier("ds1") DataSource ds1,
                                        @Qualifier("ds2") DataSource ds2) {
        //1.定义数据源map
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("ds1", ds1);
        targetDataSources.put("ds2", ds2);
        //2.实例化DynamicDataSource, 设置数据源map
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);
        //3.设置默认数据源,未匹配上则使用默认数据源
        dynamicDataSource.setDefaultTargetDataSource(ds1);
        return dynamicDataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource ds) {
        // 设置对应的数据源
        return new JdbcTemplate(ds);
    }
}